package com.ygxsk.carhome.botdialog;

/**
 * Created by shaohui on 16/10/11.
 */

import android.os.Bundle;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;

import androidx.annotation.LayoutRes;
import androidx.fragment.app.DialogFragment;
import androidx.fragment.app.FragmentManager;
import androidx.fragment.app.FragmentTransaction;

import com.blankj.utilcode.util.ActivityUtils;
import com.ygxsk.carhome.R;

import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;

//import android.support.annotation.LayoutRes;
//import android.support.v4.app.DialogFragment;
//import android.support.v4.app.FragmentManager;

/**
 * Created by shaohui on 16/10/11.
 */

public abstract class BaseBottomDialog extends DialogFragment {

    private static final String TAG = "base_bottom_dialog";

    private static final float DEFAULT_DIM = 0.2f;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setStyle(DialogFragment.STYLE_NO_TITLE, R.style.BottomDialog);
    }

    //，
    // 但onCraeteView设置的视图优先级要高于在onCreateDia可以通过重写onCreateDialog和onCreateView来设置DialogFragment的视图log。
    //设置Dialog的属性需要在onCreateDialog回调后设置，不然getDialog得到的对象则会是null,推荐在onStar方法中对Dialog进行属性设置。
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {

        getDialog().getWindow().requestFeature(Window.FEATURE_NO_TITLE);
        getDialog().setCanceledOnTouchOutside(getCancelOutside());

        View v = inflater.inflate(getLayoutRes(), container, false);
        bindView(v);
        return v;
    }


    @LayoutRes
    public abstract int getLayoutRes();

    public abstract void bindView(View v);

    @Override
    public void onStart() {
        super.onStart();

        Window window = getDialog().getWindow();
        WindowManager.LayoutParams params = window.getAttributes();

        params.dimAmount = getDimAmount();
        params.width = WindowManager.LayoutParams.MATCH_PARENT;
        if (getHeight() > 0) {
            params.height = getHeight();
        } else {
            params.height = WindowManager.LayoutParams.WRAP_CONTENT;
        }
        params.gravity = Gravity.BOTTOM;

        window.setAttributes(params);
    }

    public int getHeight() {
        return -1;
    }

    public float getDimAmount() {
        return DEFAULT_DIM;
    }

    public boolean getCancelOutside() {
        return true;
    }

    public String getFragmentTag() {
        return TAG;
    }

    //父类的show方法
    /*public void show(FragmentManager manager, String tag) {
        mDismissed = false;
        mShownByMe = true;
        FragmentTransaction ft = manager.beginTransaction();
        ft.add(this, tag);
        ft.commit();
    }*/

    //2019年09月19日因为报错需要重写  itchen 自己改造
    //自己改造的第一种解决问题的办法
    @Override
    public void show(FragmentManager manager, String tag) {

        try {

            Class clazz = Class.forName("androidx.fragment.app.DialogFragment");

            Field dismissed = clazz.getDeclaredField("mDismissed");
            Field shownByMe = clazz.getDeclaredField("mShownByMe");

            dismissed.setAccessible(true);
            shownByMe.setAccessible(true);


            Constructor constructor = clazz.getConstructor();

            Object dialogFragment = (DialogFragment) constructor.newInstance();

            dismissed.setBoolean(dialogFragment, false);
            shownByMe.setBoolean(dialogFragment, true);

            //itchen日志
            //LogUtils.d("itchen---dismissed-->"+dismissed);
            //LogUtils.d("itchen---shownByMe-->"+shownByMe);

            //LogUtils.d("itchen---dismissed-->"+dismissed.getBoolean(dialogFragment));
            //LogUtils.d("itchen---shownByMe-->"+shownByMe.getBoolean(dialogFragment));
            //itchen---dismissed-->false
            //itchen---shownByMe-->true

            FragmentTransaction ft = manager.beginTransaction();

            ft.add(this, tag);
            // 这里吧原来的commit()方法换成了commitAllowingStateLoss()
            ft.commitAllowingStateLoss();


        } catch (ClassNotFoundException e) {

            //LogUtils.d("itchen--->" + e.getLocalizedMessage());

            e.printStackTrace();


        } catch (NoSuchFieldException e) {
            // LogUtils.d("itchen--->" + e.getLocalizedMessage());

            e.printStackTrace();
        } catch (NoSuchMethodException e) {
            // LogUtils.d("itchen--->" + e.getLocalizedMessage());

            e.printStackTrace();
        } catch (java.lang.InstantiationException e) {
            //LogUtils.d("itchen--->" + e.getLocalizedMessage());

            e.printStackTrace();
        } catch (IllegalAccessException e) {
            //LogUtils.d("itchen--->" + e.getLocalizedMessage());

            e.printStackTrace();
        } catch (InvocationTargetException e) {
            //LogUtils.d("itchen--->" + e.getLocalizedMessage());

            e.printStackTrace();
        }

    }

    //第二种解决问题的办法

    /**
     * 为了解决:mainActivity调用onSaveInstanceState以后又调用了show方法,
     * 出现的Can not perform this action after onSaveInstanceState
     * 这个异常(不应该用commit ,而是用commitAllowingStateLoss)
     * 得罪了,不会反射 ,先把你catch住吧.乖
     */
    //https://blog.csdn.net/u010568407/article/details/53672046
    /*@Override
    public void show(FragmentManager manager, String tag) {

        try {

            super.show(manager, tag);

        }catch (IllegalStateException ignore) {
            //容错处理，不做操作
        }

    }*/

    //2019年09月19日因为报错需要重写：解决办法 https://www.jianshu.com/p/05f36f2fa618
    public void show(FragmentManager fragmentManager) {


        //2019年09月19日原始代码：如下一行：
        show(fragmentManager, getFragmentTag());


    }


    //最好自己也重写一个 忽略dismissAllowingStateLoss 关闭弹窗的方法
    public void dismissBottomDialog() {


        if ((getActivity() != null)) {

            //如果它的负载Activity还活着的
            if (ActivityUtils.isActivityAlive(getActivity())) {

                super.dismissAllowingStateLoss();

            }


        }


    }

}
